import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type {
  Camera,
  PageQuery,
  TreeNode,
  Device,
  StreamServer,
  MapDevice,
} from "@/types";
import { getCameraTree } from "@/api/camera";
import { $getDeviceList, $getAllDeviceInMap } from "@/api/device";
import { $getAllServer, $getStreamPreviewPort } from "@/api/nvr";
import { buildTree, findNodeById } from "@/utils/tree";
import { int } from "three/src/nodes/TSL.js";
// 从流路径中提取流名称的辅助函数
function extractStreamName(
  streamPath: string,
  streamType: "flv" | "flvsub" | "hls" | "hlssub"
): string {
  if (!streamPath) return "";

  // 去掉开头的斜杠
  const cleanPath = streamPath.startsWith("/")
    ? streamPath.substring(1)
    : streamPath;

  if (streamType === "flv" || streamType === "flvsub") {
    // FLV流路径格式: "jtlive/jt_n127000000001_c84_s0.flv"
    // 提取文件名并去掉扩展名
    const fileName = cleanPath.split("/").pop() || "";
    return fileName.replace(/\.flv$/, "");
  } else if (streamType === "hls" || streamType === "hlssub") {
    // HLS流路径格式: "hls/jt_n127000000001_c84_s0/index.m3u8"
    // 提取目录名
    const pathParts = cleanPath.split("/");
    if (pathParts.length >= 2) {
      return pathParts[1]; // 返回 "jt_n127000000001_c84_s0"
    }
    return pathParts[0] || "";
  }

  return cleanPath;
}

export const useCameraStore = defineStore("camera", () => {
  // 状态
  const cameras = ref<Camera[]>([]);
  const currentCamera = ref<Camera | null>(null);
  const loading = ref(false);
  const total = ref(0);
  const pageQuery = ref<PageQuery>({
    page: 1,
    pageSize: 20,
    keyword: "",
  });

  // 树形结构相关状态
  const cameraTree = ref<TreeNode[]>([]);
  const currentTreeNode = ref<TreeNode | null>(null);
  const treeLoading = ref(false);

  // 计算属性
  const onlineCameras = computed(() =>
    cameras.value.filter((camera: Camera) => camera.status === "online")
  );
  const offlineCameras = computed(() =>
    cameras.value.filter((camera: Camera) => camera.status === "offline")
  );
  const errorCameras = computed(() =>
    cameras.value.filter((camera: Camera) => camera.status === "error")
  );

  const statusStats = computed(() => ({
    total: cameras.value.length,
    online: onlineCameras.value.length,
    offline: offlineCameras.value.length,
    error: errorCameras.value.length,
  }));

  const flvServerList = ref<StreamServer[]>([]);

  const allDeviceInMap = ref<MapDevice[]>([]);

  //通过NvrId获取流媒体服务器列表
  const getFlvServerListByNvrId = (nvrId: number): Partial<StreamServer> => {
    const response = flvServerList.value.find((server) => server.id === nvrId);
    return response || {};
  };

  /**
   * 获取摄像头树形结构
   */
  const fetchCameraTree = async (): Promise<void> => {
    try {
      treeLoading.value = true;
      const streamPort = parseInt((await $getStreamPreviewPort()).data.realStreamPort, 10);
      flvServerList.value = (await $getAllServer()).data.map((server) => ({
        ...server,
        streamPort,
      }));
      allDeviceInMap.value = (await $getAllDeviceInMap()).data;

      // 处理设备流地址获取 - 为allDeviceInMap中的设备添加真实的流地址
      allDeviceInMap.value = allDeviceInMap.value.map((mapDevice) => {
        const server = flvServerList.value.find(
          (s) => s.id === mapDevice.nvrId
        );

        if (!server) {
          console.warn(
            `No server found for map device ${mapDevice.id} (nvrId: ${mapDevice.nvrId})`
          );
          return mapDevice;
        }

        // 构建完整的流地址
        const streamUrls = {
          flv: mapDevice.flv
            ? `http://${server.ip}:${
                server.streamPort
              }/live?port=1935&app=hls&stream=${extractStreamName(
                mapDevice.flv,
                "flv"
              )}`
            : "",
          flvsub: mapDevice.flvsub
            ? `http://${server.ip}:${
                server.streamPort
              }/live?port=1935&app=hls&stream=${extractStreamName(
                mapDevice.flvsub,
                "flvsub"
              )}`
            : "",
          hls: mapDevice.hls
            ? `http://${server.ip}:${
                server.streamPort
              }/live?port=1935&app=hls&stream=${extractStreamName(
                mapDevice.hls,
                "hls"
              )}`
            : "",
          hlssub: mapDevice.hlssub
            ? `http://${server.ip}:${
                server.streamPort
              }/live?port=1935&app=hls&stream=${extractStreamName(
                mapDevice.hlssub,
                "hlssub"
              )}`
            : "",
        };

        return {
          ...mapDevice,
          flv: streamUrls.flv,
          flvsub: streamUrls.flvsub,
          hls: streamUrls.hls,
          hlssub: streamUrls.hlssub,
        };
      });
      const response = await getCameraTree();
      const treeData = response?.data;
      const builtTree = buildTree(treeData,0,true);
      cameraTree.value = builtTree;

      // 自动获取第一个文件夹的设备数据
      if (builtTree.length > 0) {
        const firstFolder = builtTree[0];
        console.log(
          "Store: Auto-loading devices for first folder:",
          firstFolder.id,
          firstFolder.name
        );
        try {
          await fetchDevicesByNodeId(firstFolder.id);
          console.log("Store: Successfully loaded devices for first folder");
        } catch (error) {
          console.error(
            "Store: Failed to load devices for first folder:",
            error
          );
          // 不抛出错误，避免影响整体功能
        }
      }
    } catch (error) {
      console.error("Get camera tree failed:", error);
      // 设置空数组作为fallback
      cameraTree.value = [];
      throw error;
    } finally {
      treeLoading.value = false;
    }
  };

  /**
   * 根据节点ID获取设备列表
   */
  const fetchDevicesByNodeId = async (nodeId: number): Promise<Device[]> => {
    try {
      console.log(`Store: Fetching devices for node ${nodeId}`);
      const response = await $getDeviceList(nodeId.toString());
      console.log("Store: Device API response:", response);
      const rawDevices = response.data;
      console.log("Store: Raw devices data:", rawDevices);

      // // 为设备嵌入地图设备信息
      // const devicesWithMapInfo = rawDevices.map((device: Device) => {
      //   // 在 allDeviceInMap 中查找对应的地图设备信息
      //   const mapDevice = allDeviceInMap.value.find((mapDev: MapDevice) => mapDev.id === device.id)

      //   if (mapDevice) {
      //     console.log(`Store: Found map device info for device ${device.id} (${device.name})`)
      //     // 使用allDeviceInMap中已经处理过的流地址
      //     return {
      //       ...device,
      //       flv: mapDevice.flv,
      //       flvsub: mapDevice.flvsub,
      //       hls: mapDevice.hls,
      //       hlssub: mapDevice.hlssub,
      //       mapDevice: mapDevice,
      //     }
      //   }

      //   return device
      // })
      const devicesWithMapInfo = rawDevices.map((device: Device) => {
        const server = flvServerList.value.find((s) => s.id === device.nvrId);
        if (!server) {
          console.warn(
            `No server found for map device ${device.id} (nvrId: ${device.nvrId})`
          );
          return device;
        }

        // 构建完整的流地址
        const streamUrls = {
          flv: device.flv
            ? `http://${server.ip}:${
                server.streamPort
              }/live?port=1935&app=hls&stream=${extractStreamName(
                device.flv,
                "flv"
              )}`
            : "",
          flvsub: device.flvsub
            ? `http://${server.ip}:${
                server.streamPort
              }/live?port=1935&app=hls&stream=${extractStreamName(
                device.flvsub,
                "flvsub"
              )}`
            : "",
          hls: device.hls
            ? `http://${server.ip}:${
                server.streamPort
              }/live?port=1935&app=hls&stream=${extractStreamName(
                device.hls,
                "hls"
              )}`
            : "",
          hlssub: device.hlssub
            ? `http://${server.ip}:${
                server.streamPort
              }/live?port=1935&app=hls&stream=${extractStreamName(
                device.hlssub,
                "hlssub"
              )}`
            : "",
        };

        return {
          ...device,
          flv: streamUrls.flv,
          flvsub: streamUrls.flvsub,
          hls: streamUrls.hls,
          hlssub: streamUrls.hlssub,
          ptzEnable: device.ptzEnable ?? true, // 默认支持云台控制，用于测试
        };
      });
      console.log("Store: Devices with map info:", devicesWithMapInfo);

      // 更新树形结构中对应节点的设备列表
      const node = findNodeById(cameraTree.value, nodeId);
      if (node) {
        node.devices = devicesWithMapInfo;
        console.log(
          `Store: Updated node ${nodeId} with ${devicesWithMapInfo.length} devices`
        );
      } else {
        console.warn(`Store: Node ${nodeId} not found in tree`);
      }
      return devicesWithMapInfo;
    } catch (error) {
      console.error("Get devices by node id failed:", error);
      throw error;
    }
  };

  /**
   * 获取摄像头列表（保持向后兼容）
   */
  const fetchCameraList = async (): Promise<void> => {
    try {
      loading.value = true;
      // 先获取树形结构
      await fetchCameraTree();

      // 如果需要获取所有设备，可以遍历树形结构
      // 这里暂时保持原有逻辑，具体实现根据需求调整
    } catch (error) {
      console.error("Get camera list failed:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取摄像头详情
   */
  const fetchCameraDetail = async (id: number): Promise<Camera> => {
    try {
      const camera = cameras.value.find((c: Camera) => c.id === id);
      if (camera) {
        currentCamera.value = camera;
        return camera;
      }
      throw new Error("摄像头不存在");
    } catch (error) {
      console.error("Get camera detail failed:", error);
      throw error;
    }
  };

  return {
    // 状态
    cameras,
    currentCamera,
    loading,
    total,
    pageQuery,

    // 树形结构相关状态
    cameraTree,
    currentTreeNode,
    treeLoading,
    flvServerList,
    allDeviceInMap,

    // 计算属性
    onlineCameras,
    offlineCameras,
    errorCameras,
    statusStats,

    // 方法
    fetchCameraList,
    fetchCameraDetail,
    fetchCameraTree,
    fetchDevicesByNodeId,
    getFlvServerListByNvrId,
  };
});
